<?php
class APIView{
	const REQUEST = 'REQUEST_METHOD';
	const ACCEPT = 'HTTP_ACCEPT';
	const REQUEST_METHOD_GET = 'get';
	const PATH_INFO = 'PATH_INFO';
	const FORMAT_JSON = 'application/json';
	const FORMAT_XML = 'application/xml';
	const DEFAULT_XML_ROOT = 'error_flynn';
	const NOT_FOUND = 'HTTP/1.0 404 Not Found';
	
	public function getRequestMethod(){
		return strtolower($_SERVER[APIView::REQUEST]);
	}
	
	public function getHTTP_ACCEPT(){
		return strtolower($_SERVER[APIView::ACCEPT]);
	}
	
	public function GetIDValue(){
		if(isset($_SERVER[APIView::PATH_INFO])){
			$PathContent = array_merge(array_filter(explode('/', $_SERVER[APIView::PATH_INFO])));
			if(isset($PathContent[2])){
				return $PathContent[2];
			}
		}
		return NULL;
	}
	
	public function isValidUri(){
		if(isset($_SERVER[APIView::PATH_INFO])){
			$PathContent = array_merge(array_filter(explode('/', $_SERVER[APIView::PATH_INFO])));
			if($PathContent[0] === 'Position'){
				if(isset($PathContent[1])){
					if($PathContent[1] === 'Producer'){
						return TRUE; 
					}
				}
			}elseif($PathContent[0] === 'Positions'){
				if(!isset($PathContent[1])){
					return TRUE;
				}
			}
		}
		return FALSE;
	}
	public function GetNotFoundCode(){
		header(APIView::NOT_FOUND);
		header('Content-Type: '.APIView::FORMAT_XML);
		return "<".APIView::DEFAULT_XML_ROOT.">Resource Not Found</".APIView::DEFAULT_XML_ROOT.">";
	}
	
	public function FormatResult($result){
		if($result === APIView::NOT_FOUND){
			return $this->GetNotFoundCode();
		}
		if($this->getHTTP_ACCEPT() === APIView::FORMAT_JSON){
			
			header('Content-Type: '.APIView::FORMAT_JSON);
			return json_encode($result, JSON_FORCE_OBJECT);
			
		}else{
			if(is_object($result[0])){
				
				$xmlStart = "<".$this->PluralizeThis(strtolower(get_class($result[0]))).">";
				$xmlEnd = "</".$this->PluralizeThis(strtolower(get_class($result[0]))).">";
				
			}elseif(is_array($result[0])){
				
				$xmlStart = "<".APIView::DEFAULT_XML_ROOT.">";
				$xmlEnd = "</".APIView::DEFAULT_XML_ROOT.">";
				
			}
			
			$xml = $xmlStart;
			
			foreach ($result as $value){
				$xml .= $this->AssocToXML($value);
			}
			
			$xml .= $xmlEnd;
			$xml = simplexml_load_string($xml);
			header('Content-Type: '.APIView::FORMAT_XML);
			return $xml->asXML();
		}
	}
	
	public function AssocToXML($result){
		$xml = "";
		$xml .= "<".strtolower(get_class($result)).">";
		foreach ($result as $key => $value) {
			$xml .= "<$key>$value</$key>";
		}
		$xml .= "</".strtolower(get_class($result)).">";
		return $xml;
	}
	
	public function PluralizeThis($string){
		if(is_string($string)){
			$string = $string."result";
		}
		return $string;
	}
}
?>